package com.imooc.sm.global;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
        // 如果是登录页面，则直接放行
        if (path.toLowerCase().indexOf("login") != -1){
            filterChain.doFilter(request, response);
        }
        // 获取session中的用户信息
        Object user = request.getSession().getAttribute("USER");
        if (user != null){
            // 如果session里有用户数据，则直接放行
            filterChain.doFilter(request, response);
        }else {
            // 否则跳转到登录页面
            response.sendRedirect(request.getContextPath() + "/toLogin.do");
        }
    }

    @Override
    public void destroy() {

    }
}
